package gui.parser;

import java.awt.Color;
import java.util.regex.Pattern;

public class ColorFactory {
	/**
	 * 解析字符串获得颜色
	 * 
	 * @param colorString
	 * @return
	 */
	public static Color build(String colorString) {
		Color c = null;
		if (colorString != null && colorString.startsWith("#")) {
			if (Pattern.matches("#[0-9a-fA-F]{6}", colorString)) {
				c = new Color(Integer.parseInt(colorString.substring(1, 3), 16), // r
						Integer.parseInt(colorString.substring(3, 5), 16), // g
						Integer.parseInt(colorString.substring(5, 7), 16));// b
			} else if (Pattern.matches("#[0-9a-fA-F]{3}", colorString)) {
				c = new Color(Integer.parseInt(colorString.charAt(1) + "" + colorString.charAt(1), 16), // r
						Integer.parseInt(colorString.charAt(2) + "" + colorString.charAt(2), 16), // g
						Integer.parseInt(colorString.charAt(3) + "" + colorString.charAt(3), 16));// b
			} else if (Pattern.matches("#[0-9a-fA-F]{4}", colorString)) {
				c = new Color(Integer.parseInt(colorString.charAt(2) + "" + colorString.charAt(2), 16), // r
						Integer.parseInt(colorString.charAt(3) + "" + colorString.charAt(3), 16), // g
						Integer.parseInt(colorString.charAt(4) + "" + colorString.charAt(4), 16), // b
						Integer.parseInt(colorString.charAt(1) + "" + colorString.charAt(1), 16));// a
			} else if (Pattern.matches("#[0-9a-fA-F]{8}", colorString)) {
				c = new Color(Integer.parseInt(colorString.substring(3, 5), 16), // r
						Integer.parseInt(colorString.substring(5, 7), 16), // g
						Integer.parseInt(colorString.substring(7, 9), 16), // b
						Integer.parseInt(colorString.substring(1, 3), 16));// a
			}
		}
		return c;
	}
}
